package com.lmb.controller;

import com.lmb.bean.UserLogin;
import com.lmb.mapper.UserLoginDao;
import com.lmb.service.LoginService;
import com.lmb.service.UserLoginService;
import com.lmb.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@RestController
@RequestMapping("/login")
@CrossOrigin

public class LoginController {

    @Autowired
    LoginService loginService;
    @Autowired
    UserLoginDao userLoginDao;
    @Autowired
    private UserLoginService userLoginService;

    @GetMapping("/captcha")
    public Object getCaptcha(){
        return Result.success(CaptchaUtil.getCaptcha());
    }
    @PostMapping("/dologin")
    public Result login(UserLogin userLogin, @RequestParam("captcha") String captcha, @RequestParam("key") String key){
        //验证验证码
        if (!CaptchaUtil.checkCaptcha(key,captcha)){
            return Result.fail(500,"验证码错误");
        }
        //登录
        try {
            String token = loginService.login(userLogin);
            //删除验证码
            return Result.success("登陆成功",token);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(500,e.getMessage());
        }
    }
    @GetMapping("/getlogin")
    public Result getlogin(HttpServletRequest request, HttpSession session){//获取登录信息
        String token=request.getHeader(SyS.TOKEN_AUTHORIZATION);//获取token
        try {
            UserLogin userLogin=loginService.getlogin(token);
            return Result.success(userLogin);
        }catch (RuntimeException e) {
            TokenUtil.removeToken(token);
            return Result.fail(500,e.getMessage());
        } catch (Exception e) {
            return Result.fail(500,"登录异常：系统错误");
        }

    }
    // 新增：用于存储验证码（5分钟有效期）
    private static ExpiryMap captchaCache = new ExpiryMap(300000);

    /**
     * 新增：发送重置密码验证码
     */
    @GetMapping("/sendResetCaptcha")
    public Result sendResetCaptcha(@RequestParam("user_name") String user_name) {
        UserLogin user = userLoginDao.getByusername(user_name);
        if (user == null) {
            return Result.fail(404, "用户不存在");
        }
        if (user.getEmail() == null || user.getEmail().isEmpty()) {
            return Result.fail(400, "用户未绑定邮箱");
        }

        // 生成6位随机验证码
        String captcha = String.valueOf(new Random().nextInt(900000) + 100000);
        // 存储验证码
        captchaCache.put(user_name, captcha,60000);
        // 发送邮件
        EmailUtil.sendEmail(user.getEmail(), captcha);
        return Result.success("验证码已发送");
    }

    /**
     * 新增：确认重置密码
     */
    @PostMapping("/confirmReset")
    public Result confirmReset(@RequestBody UserLogin user) {
        String user_name = user.getUser_name();
        String captcha1 = user.getUser_password(); // 临时用password字段传验证码
        System.out.println(user_name);
        System.out.println(captcha1);
        if (user_name == null || captcha1 == null) {
            return Result.fail(400, "参数错误");
        }
        // 验证验证码
        String cachedCaptcha = (String) captchaCache.get(user_name);
        System.out.println(cachedCaptcha);
        if (cachedCaptcha == null || !cachedCaptcha.equals(captcha1)) {
            return Result.fail(400, "验证码错误或已过期");
        }

        // 重置密码为123456（加密存储）
        UserLogin dbUser = userLoginDao.getByusername(user_name);
        dbUser.setUser_password(PasswordUtil.getEncryption("123456"));
        userLoginService.edit(dbUser);

        // 清除验证码
        captchaCache.remove(user_name);
        return Result.success("密码重置成功");
    }
    //注册
    @GetMapping("/sendRegisterCaptcha")
    public Result sendRegisterCaptcha(@RequestParam("user_name") String userName, @RequestParam("email") String email) {
        // 检查用户名是否已存在
        if (userLoginDao.getByusername(userName) != null) {
            return Result.fail(400, "用户名已存在");
        }
        // 生成6位验证码
        String captcha = String.valueOf(new Random().nextInt(900000) + 100000);
        // 存储验证码（使用独立缓存键前缀避免与重置密码验证码冲突）
        captchaCache.put("register_" + userName, captcha, 60000);
        // 发送邮件
        EmailUtil.sendEmail(email, captcha);
        return Result.success("注册验证码已发送");
    }


    @PostMapping("/register")
    public Result register(@RequestBody UserLogin user) {
        String userName = user.getUser_name();
        String captcha = user.getCaptcha();

        // 1. 验证用户名是否已存在
        if (userLoginDao.getByusername(userName) != null) {
            return Result.fail(400, "用户名已存在");
        }

        // 2. 验证验证码
        String cachedCaptcha = (String) captchaCache.get("register_" + userName);
        if (cachedCaptcha == null || !cachedCaptcha.equals(captcha)) {
            return Result.fail(400, "验证码错误或已过期");
        }

        try {
            // 3. 密码加密
            user.setUser_password(PasswordUtil.getEncryption(user.getUser_password()));
            // 4. 保存用户信息
            userLoginService.add(user);
            // 5. 清除验证码
            captchaCache.remove("register_" + userName);
            return Result.success("注册成功");
        } catch (org.springframework.dao.DuplicateKeyException e) {
            // 专门捕获唯一键冲突异常（双重保障）
            return Result.fail(400, "该用户名已被占用，请尝试更换用户名");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "注册失败：系统错误");
        }
    }


}

